import React, { useRef, useState } from 'react';
import _ from 'lodash';
import { Button, Dropdown, Menu, message, Popconfirm } from 'antd';
import CommonTable from '@/components/CommonTable';
import DepartmentModal from './components/departmentModal';
import DebounceWrapper from '@/components/DebounceWrapper';
import {
  LinkOutlined,
  DeleteOutlined,
  EditOutlined,
  PlusOutlined,
  MoreOutlined,
} from '@ant-design/icons';
import RoleRelationDrawer from './components/roleRelationDrawer';
import JobRelationDrawer from './components/jobRelationDrawer';
import { fetchDepartmentList, deleteDepartment } from '@/services/system/department';

const DebounceButton = DebounceWrapper(Button);
// 添加序号
const addTreeIndex = (tree = [], indexString = '', arr = []) => {
  if (!tree.length) return [];
  tree.forEach((item, index) => {
    const node = { ...item };
    delete node.children;
    const currentIndex = indexString ? `${indexString}-${index + 1}` : index + 1;
    node.customIndex = currentIndex;
    if (item.children && item.children.length) {
      node.children = [];
      arr.push(node);
      addTreeIndex(item.children, currentIndex, node.children);
    } else {
      arr.push(node);
    }
  });
  return arr;
};

export default () => {
  const tableRef = useRef(null);
  const [deleteLoadingIds, setDeleteLoadingIds] = useState([]);
  const [departmentModalOptions, setDepartmentModalOptions] = useState({});
  const [departmentModalVisible, setDepartmentModalVisible] = useState(false);

  const [roleRelationDrawerWithDepartmentId, setRoleRelationDrawerWithDepartmentId] = useState('');
  const [jobRelationDrawerWithDepartmentId, setJobRelationDrawerWithDepartmentId] = useState('');

  // 切换loading
  const toggleDeleteLoading = (id, status) => {
    setDeleteLoadingIds((list) => {
      const nextList = [...list];
      if (status) {
        nextList.push(id);
      } else {
        const index = _.indexOf(nextList, id);
        if (index > -1) {
          nextList.splice(index, 1);
        }
      }
      return nextList;
    });
  };

  return (
    <>
      <CommonTable
        ref={tableRef}
        rowKey={'id'}
        paging={false}
        header={{
          headerTitle: '机构/部门列表',
          headerToolsRender: true,
          headerButtonList: [
            {
              key: 'add',
              type: 'primary',
              label: '新增',
              icon: <PlusOutlined />,
            },
          ],
          headerButtonClick: async ({ key }) => {
            switch (key) {
              case 'add':
                setDepartmentModalVisible(true);
                break;
            }
          },
        }}
        request={async (params) => {
          const treeData = await fetchDepartmentList(params);
          return { data: addTreeIndex(treeData) };
        }}
        columns={[
          { title: '序号', dataIndex: 'customIndex', align: 'left', width: 120 },
          { title: '机构/部门名称', dataIndex: 'organName', columnControl: { typeList: 'search' } },
          { title: '机构/部门编码', dataIndex: 'organCode', columnControl: { typeList: 'search' } },
          {
            title: '机构形式',
            dataIndex: 'formType',
            columnControl: { typeList: 'filter', filterDictType: 'form_type' },
          },
          { title: '详细地址', dataIndex: 'address' },
          {
            title: '操作',
            dataIndex: 'id',
            width: 240,
            render: (text, data) => {
              const deleteLoading = _.includes(deleteLoadingIds, text);
              return (
                <>
                  <DebounceButton
                    type="link"
                    size="small"
                    icon={<EditOutlined />}
                    disabled={deleteLoading}
                    onClick={() => {
                      setDepartmentModalOptions(data);
                      setDepartmentModalVisible(true);
                    }}
                  >
                    查看/编辑
                  </DebounceButton>
                  <Popconfirm
                    okText="确定"
                    cancelText="取消"
                    title={'确认删除该机构节点，删除后不可恢复'}
                    placement="topRight"
                    onConfirm={async () => {
                      toggleDeleteLoading(text, true);
                      try {
                        await deleteDepartment({ id: text });
                        const { refresh } = tableRef.current;
                        refresh && refresh();
                        message.success('机构节点删除成功');
                      } catch (e) {
                        console.log('删除失败');
                      }
                      toggleDeleteLoading(text, false);
                    }}
                  >
                    <DebounceButton
                      danger
                      type="link"
                      size="small"
                      icon={<DeleteOutlined />}
                      loading={deleteLoading}
                    >
                      删除
                    </DebounceButton>
                  </Popconfirm>
                  <Dropdown
                    trigger={['click']}
                    disabled={deleteLoading}
                    overlay={
                      <Menu
                        items={[
                          { key: 'roleRelation', icon: <LinkOutlined />, label: '已关联角色' },
                          {
                            key: 'jobRelation',
                            icon: <LinkOutlined />,
                            label: '已关联岗位',
                          },
                        ]}
                        onClick={({ key }) => {
                          switch (key) {
                            case 'roleRelation':
                              setRoleRelationDrawerWithDepartmentId(text);
                              break;
                            case 'jobRelation':
                              setJobRelationDrawerWithDepartmentId(text);
                              break;
                          }
                        }}
                      />
                    }
                  >
                    <DebounceButton type="text" size="small">
                      更多
                      <MoreOutlined />
                    </DebounceButton>
                  </Dropdown>
                </>
              );
            },
          },
        ]}
      />
      <DepartmentModal
        visible={departmentModalVisible}
        options={departmentModalOptions}
        closeModal={() => {
          setDepartmentModalOptions({});
          setDepartmentModalVisible(false);
        }}
        updateList={() => {
          const { refresh } = tableRef.current;
          refresh && refresh();
        }}
      />
      <RoleRelationDrawer
        visible={!!roleRelationDrawerWithDepartmentId}
        departmentId={roleRelationDrawerWithDepartmentId}
        closeDrawer={() => {
          setRoleRelationDrawerWithDepartmentId('');
        }}
      />
      <JobRelationDrawer
        visible={!!jobRelationDrawerWithDepartmentId}
        departmentId={jobRelationDrawerWithDepartmentId}
        closeDrawer={() => {
          setJobRelationDrawerWithDepartmentId('');
        }}
      />
    </>
  );
};
